package org.darcy.service.impl;

import org.darcy.dao.SysUserRoleMapper;
import org.darcy.entity.SysUserRole;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 用户角色
 *
 */
@Service
public class SysUserRoleServiceImpl extends GenericServiceImpl<SysUserRole> implements SysUserRoleService {

	@Autowired
	private SysUserRoleMapper resourceMapper;

	/**
	 * 添加用户角色
	 *
	 * @param userId
	 * @param roleIds
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void addUserRole(Long userId, String roleIds) {
		// 删除
		removeByUserId(userId);
		// 添加
		String[] roleIdArr = roleIds.split(",");
		if (roleIdArr.length == 0) {
			return;
		}
		SysUserRole u = null;
		for (String roleId : roleIdArr) {
			u = new SysUserRole();
			u.setUserId(userId);
			u.setRoleId(Long.parseLong(roleId));
			this.insert(u);
		}
	}

	/**
	 * 根据用户ID删除用户角色
	 *
	 * @param userId
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public void removeByUserId(Long userId) {
		QueryWrapper<SysUserRole> q = new QueryWrapper<SysUserRole>();
		q.eq("user_id", userId);
		resourceMapper.delete(q);
	}
}
